/**
 * 文本生成工具 - IntelliMark适配版
 * 提供专业的Markdown文本生成功能
 */

import { BaseTool, ToolResult, ToolResultMetadata } from "../../types/tools";
import { getEnhancedAIProviderManager } from "../../utils/aiProviderAdapter";
import { formatPrompt } from "../../utils/promptTemplates";
import { HumanMessage, SystemMessage } from "@langchain/core/messages";
import { v4 as uuidv4 } from 'uuid';

// 文本生成操作类型
export type TextGenerationOperation =
  | 'polish'        // 润色
  | 'expand'        // 扩写
  | 'continue'      // 续写
  | 'summarize'     // 摘要
  | 'generate'      // 生成
  | 'rewrite'       // 改写
  | 'outline'       // 大纲
  | 'translate';    // 翻译

// 文本生成参数
export interface TextGenerationParams {
  operation: TextGenerationOperation;
  text?: string;
  prompt?: string;
  style?: 'formal' | 'casual' | 'academic' | 'creative' | 'technical' | 'neutral';
  tone?: 'neutral' | 'positive' | 'negative' | 'persuasive' | 'informative';
  length?: 'short' | 'medium' | 'long';
  targetLength?: number;
  context?: string;
  language?: string;
  targetLanguage?: string; // for translation
}

// 文本生成工具配置
export interface TextGenerationConfig {
  defaultProvider: string;
  maxTokens: number;
  temperature: number;
  enableCache: boolean;
  cacheTimeout: number; // 秒
}

export class TextGenerationTool extends BaseTool {
  private config: TextGenerationConfig;
  private cache: Map<string, { result: string; timestamp: number }> = new Map();

  constructor(config: Partial<TextGenerationConfig> = {}) {
    super();

    this.name = 'text-generation';
    this.description = '专业的IntelliMark文本生成工具，支持润色、扩写、续写、摘要、创作、翻译等多种Markdown文本生成任务';
    this.category = 'textGeneration';
    this.enabled = true;
    this.requiresAuth = false;

    this.config = {
      defaultProvider: 'openai-gpt4',
      maxTokens: 4000,
      temperature: 0.7,
      enableCache: true,
      cacheTimeout: 3600, // 1小时
      ...config,
    };

    this.parameters = [
      {
        name: 'operation',
        type: 'string' as const,
        description: '文本生成操作类型',
        required: true,
        validation: {
          enum: ['polish', 'expand', 'continue', 'summarize', 'generate', 'rewrite', 'outline', 'translate'],
        },
      },
      {
        name: 'text',
        type: 'string' as const,
        description: '输入的Markdown文本内容',
        required: false,
      },
      {
        name: 'prompt',
        type: 'string' as const,
        description: '生成提示词（用于generate操作）',
        required: false,
      },
      {
        name: 'style',
        type: 'string' as const,
        description: '写作风格',
        required: false,
        default: 'neutral',
        validation: {
          enum: ['formal', 'casual', 'academic', 'creative', 'technical', 'neutral'],
        },
      },
      {
        name: 'tone',
        type: 'string' as const,
        description: '语调',
        required: false,
        default: 'neutral',
        validation: {
          enum: ['neutral', 'positive', 'negative', 'persuasive', 'informative'],
        },
      },
      {
        name: 'length',
        type: 'string' as const,
        description: '输出长度',
        required: false,
        default: 'medium',
        validation: {
          enum: ['short', 'medium', 'long'],
        },
      },
      {
        name: 'targetLength',
        type: 'number' as const,
        description: '目标字数',
        required: false,
        validation: {
          min: 10,
          max: 10000,
        },
      },
      {
        name: 'context',
        type: 'string' as const,
        description: '上下文信息',
        required: false,
      },
      {
        name: 'language',
        type: 'string' as const,
        description: '源语言',
        required: false,
        default: 'zh-CN',
      },
      {
        name: 'targetLanguage',
        type: 'string' as const,
        description: '目标语言（用于翻译）',
        required: false,
        default: 'en',
      },
    ];
  }

  async execute(input: any): Promise<ToolResult> {
    const startTime = Date.now();
    const requestId = uuidv4();

    try {
      // 验证输入参数
      const validatedInput = this.validateInput(input);

      // 生成缓存键
      const cacheKey = this.generateCacheKey(validatedInput);

      // 检查缓存
      if (this.config.enableCache) {
        const cachedResult = this.getCachedResult(cacheKey);
        if (cachedResult) {
          return {
            success: true,
            data: cachedResult,
            metadata: {
              cacheHit: true,
              executionTime: Date.now() - startTime,
              requestId,
            },
          };
        }
      }

      // 执行文本生成
      const result = await this.performGeneration(validatedInput);

      // 缓存结果
      if (this.config.enableCache) {
        this.cacheResult(cacheKey, result);
      }

      const executionTime = Date.now() - startTime;

      return {
        success: true,
        data: result,
        metadata: {
          executionTime,
          operation: validatedInput.operation,
          model: this.config.defaultProvider,
          cacheHit: false,
          requestId,
          inputLength: validatedInput.text?.length || validatedInput.prompt?.length || 0,
          outputLength: result.length,
        },
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);

      return {
        success: false,
        error: errorMessage,
        metadata: {
          executionTime: Date.now() - startTime,
          requestId,
        },
      };
    }
  }

  private validateInput(input: any): TextGenerationParams {
    const validated: any = {};

    // 验证必需参数
    if (!input.operation) {
      throw new Error('operation参数是必需的');
    }

    const validOperations: TextGenerationOperation[] = ['polish', 'expand', 'continue', 'summarize', 'generate', 'rewrite', 'outline', 'translate'];
    if (!validOperations.includes(input.operation)) {
      throw new Error(`无效的operation: ${input.operation}`);
    }

    validated.operation = input.operation;

    // 根据操作类型验证必需参数
    if (input.operation !== 'generate' && input.operation !== 'outline' && !input.text) {
      throw new Error(`${input.operation}操作需要text参数`);
    }

    if ((input.operation === 'generate' || input.operation === 'outline') && !input.prompt) {
      throw new Error(`${input.operation}操作需要prompt参数`);
    }

    // 验证并复制其他参数
    const stringFields = ['text', 'prompt', 'style', 'tone', 'length', 'context', 'language', 'targetLanguage'];
    stringFields.forEach(field => {
      if (input[field] !== undefined) {
        validated[field] = String(input[field]);
      }
    });

    if (input.targetLength !== undefined) {
      const targetLength = parseInt(input.targetLength);
      if (isNaN(targetLength) || targetLength < 10 || targetLength > 10000) {
        throw new Error('targetLength必须在10-10000之间');
      }
      validated.targetLength = targetLength;
    }

    return validated;
  }

  private async performGeneration(params: TextGenerationParams): Promise<string> {
    const providerManager = getEnhancedAIProviderManager();

    // 构建系统提示词
    const systemPrompt = this.buildSystemPrompt(params);

    // 构建用户提示词
    const userPrompt = this.buildUserPrompt(params);

    // 构建消息
    const messages = [
      new SystemMessage(systemPrompt),
      new HumanMessage(userPrompt)
    ];

    // 调用AI服务
    const response = await providerManager.generateEnhancedResponse(
      messages,
      this.config.defaultProvider,
      {
        temperature: this.config.temperature,
        maxTokens: this.config.maxTokens,
      }
    );

    return response.content;
  }

  private buildSystemPrompt(params: TextGenerationParams): string {
    // 根据操作类型获取对应的提示词模板
    const templateMap = {
      'polish': 'text-polish',
      'expand': 'text-expand',
      'continue': 'content-continue',
      'summarize': 'text-summarize',
      'generate': 'markdown-generator',
      'rewrite': 'text-polish', // 改写可以复用润色模板
      'outline': 'content-outline',
      'translate': 'text-polish', // 翻译使用自定义逻辑
    };

    const templateId = templateMap[params.operation];
    if (templateId && templateId !== 'text-polish' && templateId !== 'translate') {
      const template = formatPrompt(templateId, {});
      return template || '你是一个专业的文本写作助手。';
    }

    // 特殊处理
    switch (params.operation) {
      case 'polish':
      case 'rewrite':
        return `你是一个专业的文本润色专家，擅长改进Markdown文档的表达质量、语法结构和可读性。请保持原意不变，优化语言表达和格式。`;

      case 'translate':
        return `你是一个专业的翻译专家，擅长Markdown文档的翻译。请保持格式正确，确保翻译的准确性和自然性。`;

      default:
        return '你是一个专业的文本写作助手。';
    }
  }

  private buildUserPrompt(params: TextGenerationParams): string {
    const operation = params.operation;

    // 根据操作类型构建不同的提示词
    switch (operation) {
      case 'polish':
      case 'rewrite':
        return formatPrompt('text-polish', {
          text: params.text || '',
        }) || `请润色以下Markdown文本：\n\n${params.text}`;

      case 'expand':
        return formatPrompt('text-expand', {
          text: params.text || '',
          expansion_direction: params.context || '增加更多细节和描述',
          target_length: params.targetLength?.toString() || '500',
        }) || `请扩写以下Markdown文本：\n\n${params.text}`;

      case 'continue':
        return formatPrompt('content-continue', {
          existing_content: params.text || '',
          context: params.context || '无特定上下文',
          target_length: params.targetLength?.toString() || '500',
        }) || `请续写以下Markdown内容：\n\n${params.text}`;

      case 'summarize':
        return formatPrompt('text-summarize', {
          text: params.text || '',
          target_length: params.targetLength?.toString() || '200',
          summary_type: '内容摘要',
        }) || `请为以下Markdown文本生成摘要：\n\n${params.text}`;

      case 'generate':
        return `请根据以下提示生成Markdown内容：\n\n提示：${params.prompt}\n\n风格：${params.style || 'neutral'}\n语调：${params.tone || 'neutral'}\n长度：${params.length || 'medium'}`;

      case 'outline':
        return formatPrompt('content-outline', {
          topic: params.prompt || '',
          document_type: params.style || 'general',
          target_audience: params.context || 'general',
        }) || `请为以下主题生成Markdown大纲：\n\n主题：${params.prompt}`;

      case 'translate':
        return `请将以下Markdown文本从${params.language || '中文'}翻译为${params.targetLanguage || '英文'}，保持格式正确：\n\n${params.text}`;

      default:
        return params.text || params.prompt || '';
    }
  }

  private generateCacheKey(params: TextGenerationParams): string {
    const keyData = {
      operation: params.operation,
      text: params.text,
      prompt: params.prompt,
      style: params.style,
      tone: params.tone,
      length: params.length,
      targetLength: params.targetLength,
      context: params.context,
      language: params.language,
      targetLanguage: params.targetLanguage,
    };
    return Buffer.from(JSON.stringify(keyData)).toString('base64');
  }

  private getCachedResult(cacheKey: string): string | null {
    const cached = this.cache.get(cacheKey);
    if (!cached) {
      return null;
    }

    const now = Date.now();
    if (now - cached.timestamp > this.config.cacheTimeout * 1000) {
      this.cache.delete(cacheKey);
      return null;
    }

    return cached.result;
  }

  private cacheResult(cacheKey: string, result: string): void {
    this.cache.set(cacheKey, {
      result,
      timestamp: Date.now(),
    });

    // 清理过期缓存
    this.cleanExpiredCache();
  }

  private cleanExpiredCache(): void {
    const now = Date.now();
    const expiredKeys: string[] = [];

    this.cache.forEach((cached, key) => {
      if (now - cached.timestamp > this.config.cacheTimeout * 1000) {
        expiredKeys.push(key);
      }
    });

    expiredKeys.forEach(key => this.cache.delete(key));
  }

  // 公共方法
  public clearCache(): void {
    this.cache.clear();
  }

  public getCacheSize(): number {
    return this.cache.size;
  }

  public updateConfig(newConfig: Partial<TextGenerationConfig>): void {
    this.config = { ...this.config, ...newConfig };
  }

  public async *executeStream(input: any): AsyncGenerator<string, void, unknown> {
    const startTime = Date.now();
    const requestId = uuidv4();

    try {
      const validatedInput = this.validateInput(input);
      const providerManager = getEnhancedAIProviderManager();

      const systemPrompt = this.buildSystemPrompt(validatedInput);
      const userPrompt = this.buildUserPrompt(validatedInput);

      const messages = [
        new SystemMessage(systemPrompt),
        new HumanMessage(userPrompt)
      ];

      const stream = providerManager.generateEnhancedStream(
        messages,
        this.config.defaultProvider,
        {
          temperature: this.config.temperature,
          maxTokens: this.config.maxTokens,
        }
      );

      let fullResponse = '';

      for await (const chunk of stream) {
        fullResponse += chunk;
        yield chunk;
      }

      // 缓存完整结果
      if (this.config.enableCache) {
        const cacheKey = this.generateCacheKey(validatedInput);
        this.cacheResult(cacheKey, fullResponse);
      }

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      throw new Error(`文本生成流式处理失败: ${errorMessage}`);
    }
  }
}

// 导出便捷函数
export const createTextGenerationTool = (config?: Partial<TextGenerationConfig>): TextGenerationTool => {
  return new TextGenerationTool(config);
};

// 默认实例
export const defaultTextGenerationTool = new TextGenerationTool();